package com.cskaoyan.market.controller;

import com.cskaoyan.market.bo.CreateGoodsInfoBo;
import com.cskaoyan.market.bo.MarketGoodsBo;
import com.cskaoyan.market.util.HttpUtil;
import com.cskaoyan.market.vo.MarketGoodsCatAndBrandVo;
import com.cskaoyan.market.db.domain.MarketGoods;
import com.cskaoyan.market.db.domain.MarketGoodsAttribute;
import com.cskaoyan.market.db.domain.MarketGoodsProduct;
import com.cskaoyan.market.db.domain.MarketGoodsSpecification;
import com.cskaoyan.market.service.MarketGoodsService;
import com.cskaoyan.market.service.impl.MarketGoodsServiceImpl;
import com.cskaoyan.market.util.GetRequestBody;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品管理
 *
 * @author lanch
 * @since 2023/05/07 11:51
 */
@WebServlet("/admin/goods/*")
public class AdminGoodsController extends HttpServlet {

    private MarketGoodsService goodsService = new MarketGoodsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/goods/", "");
        if ("list".equals(op)) {
            showList(req, resp);
        } else if ("detail".equals(op)) {
            showDetail(req, resp);
        } else if ("catAndBrand".equals(op)) {
            catAndBrand(req, resp);
        }
    }

    //获取分类和制造商列表
    private void catAndBrand(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> catAndBrand = goodsService.getCatAndBrand();
        Object ok = ResponseUtil.ok(catAndBrand);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String s = objectMapper.writeValueAsString(ok);
        resp.getWriter().println(s);
    }

    //查询商品详细信息
    private void showDetail(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //todo;参数校验
        Integer id = Integer.parseInt(req.getParameter("id"));
        Map<String, Object> result = new HashMap<>();
        result = goodsService.getGoodsDetail(id);
        List<Object> goodsDetails = new ArrayList<>();
        // result.put("categoryIds",categoryIds);
        // result.put("goods",targetGoods);
        // result.put("attributes",attributes);
        // result.put("specification",specifications);
        // result.put("products",products);

        goodsDetails.add(result.get("categoryIds"));
        goodsDetails.add(result.get("goods"));
        goodsDetails.add(result.get("attributes"));
        goodsDetails.add(result.get("specification"));
        goodsDetails.add(result.get("products"));

        Object ok = ResponseUtil.ok(result);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/goods/", "");
        if ("update".equals(op)) {
            updateGoods(req, resp);
        } else if ("delete".equals(op)) {
            deleteGoods(req, resp);
        }else if ("create".equals(op)) {
            create(req, resp);
        }
    }
    //删除一件商品
    private void deleteGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //    请求参数为json字符串，需要到请求体里面获取
        //传入请求和一个对象，获取到请求体里面的json字符串转化为一个和传入对象相同类的实例对象
        MarketGoods o = (MarketGoods) GetRequestBody.getReqBodyObject(req, new MarketGoods());
        goodsService.deleteGoodsById(o, o.getId());
        Object ok = ResponseUtil.ok();
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));

    }
    //更改商品信息
    private void updateGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String reqBodyString = GetRequestBody.getReqBodyString(req);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        //获取marketGoodsBo对象
        MarketGoodsBo marketGoodsBo = objectMapper.readValue(reqBodyString, MarketGoodsBo.class);
        //参数校验
        //商品名不能为空
        MarketGoods goods = marketGoodsBo.getGoods();
        if(StringUtils.isEmpty(goods.getName())){
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //商品参数名不能为空
        List<MarketGoodsAttribute> attributes = marketGoodsBo.getAttributes();
        for (MarketGoodsAttribute attribute : attributes) {
            if(StringUtils.isEmpty(attribute.getAttribute())){
                resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
                return;
            }
        }
        //商品规格名不能为空
        List<MarketGoodsSpecification> specifications = marketGoodsBo.getSpecifications();
        for (MarketGoodsSpecification specification : specifications) {
            if(StringUtils.isEmpty(specification.getSpecification())){
                resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
                return;
            }
        }
        //库存数量不能为空
        List<MarketGoodsProduct> products = marketGoodsBo.getProducts();
        for (MarketGoodsProduct product : products) {
            if(StringUtils.isEmpty(""+product.getNumber())){
                resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
                return;
            }
        }

        goodsService.updateGoods(marketGoodsBo);
        Object ok = ResponseUtil.ok();
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    //todo:参数校验
    //查询商品列表；查询复用该接口，所以会多id.sn,name几个参数
    private void showList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageString = req.getParameter("page");
        String limitString = req.getParameter("limit");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        String goodsId = req.getParameter("goodsId");
        String goodsSn = req.getParameter("goodsSn");
        String name = req.getParameter("name");
        //todo:参数校验
        // page和limit必须都不为空且能转化为数字
        // if (!StringUtils.isEmpty(page) && !StringUtils.isEmpty(limit)){ }
        Integer page = null;
        Integer limit = null;
        try {
            //    校验page和limit不能为空切必须能转化为integer类型
            page = Integer.parseInt(pageString);
            limit = Integer.parseInt(limitString);
        } catch (Exception e) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        //校验sort和order如果为空则复默认值add_time和desc
        if (StringUtils.isEmpty(sort)) {
            sort = "add_time";
        }
        if (StringUtils.isEmpty(order)) {
            sort = "desc";
        }
        List<MarketGoods> goodsList = goodsService.getGoods(page, limit, sort, order, goodsSn, name, goodsId);
        Object o = ResponseUtil.okList(goodsList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtil.getRequestBody(req);
        CreateGoodsInfoBo createGoodsInfoBo = JacksonUtil.getObjectMapper().readValue(requestBody, CreateGoodsInfoBo.class);
        MarketGoods goods = createGoodsInfoBo.getGoods();
        List<MarketGoodsSpecification> specifications = createGoodsInfoBo.getSpecifications();
        for (MarketGoodsSpecification specification : specifications) {
            specification.setGoodsId(Integer.parseInt(goods.getGoodsSn()));
        }
        List<MarketGoodsProduct> products = createGoodsInfoBo.getProducts();
        for (MarketGoodsProduct product : products) {
            product.setGoodsId(Integer.parseInt(goods.getGoodsSn()));
        }
        List<MarketGoodsAttribute> attributes = createGoodsInfoBo.getAttributes();
        for (MarketGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(Integer.parseInt(goods.getGoodsSn()));
        }
        System.out.println(createGoodsInfoBo.getGoods());
        int marketGoods1 = goodsService.createMarketGoods(goods);
        int marketGoodsSpecification1 = goodsService.createMarketGoodsSpecifications(specifications);
        int marketGoodsProduct1 = goodsService.createMarketGoodsProduct(products);
        int marketGoodsAttribute1 = goodsService.createMarketGoodsAttribute(attributes);
        Object res = null;
        System.out.println(marketGoods1 + marketGoodsSpecification1 + marketGoodsProduct1 + marketGoodsAttribute1);
        if (marketGoods1>0&& marketGoodsSpecification1>0&& marketGoodsProduct1>0&& marketGoodsAttribute1>0) {
            res = ResponseUtil.ok();
        } else {
            res = ResponseUtil.fail();
        }
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        String s = objectMapper.writeValueAsString(res);
        resp.getWriter().println(s);
    }
}
